import { defineStore } from 'pinia'
import type { Settings as SettingsType } from './index'

const toPlainSettings = (s: SettingsType): SettingsType => ({
  fontSize: Number(s.fontSize),
  editorWidth: Number(s.editorWidth),
  theme: s.theme === 'dark' ? 'dark' : 'light'
})

const LOCAL_STORAGE_KEY = 'markgod:settings'

export interface FileInfo {
  path: string
  content: string
}

export interface Settings {
  fontSize: number
  editorWidth: number
  theme: 'light' | 'dark'
}

interface AppState {
  currentFile: FileInfo
  editorContent: string
  isModified: boolean
  settings: Settings
  loading: boolean // 添加loading状态
  showEditor: boolean
  showPreview: boolean
}

const DEFAULT_CONTENT = `# 欢迎使用 Markgod 编辑器 🎉

> 一款简洁、高效、支持实时预览的 Markdown 编辑器

## 快速上手

- 在左侧编辑区输入 **Markdown** 语法，右侧即刻渲染。
- 顶部工具栏可调整 **字体大小**、**主题** 与 **分栏比例**。
- 文件支持 **本地打开**、**保存**、**导出 PDF** 等操作。
- 多窗口同步：同一浏览器内多个标签页的主题与设置实时共享。

## 常用语法示例

### 标题
\`\`\`markdown
# 一级标题
## 二级标题
### 三级标题
\`\`\`

### 列表
- 无序列表项 A
- 无序列表项 B
1. 有序列表项 1
2. 有序列表项 2

### 代码块
\`\`\`ts
const greeting = 'Hello, Markgod!'
console.log(greeting)
\`\`\`

### 表格
| 快捷键 | 功能         |
| ------ | ------------ |
| Ctrl+S | 快速保存文件 |
| Ctrl+P | 导出 PDF     |

### 任务清单
- [x] 编写文档
- [ ] 提交审核
- [ ] 发布上线

现在，把光标放在左侧，开始你的创作之旅吧！
`

export const useAppStore = defineStore('app', {
  state: (): AppState => ({
    currentFile: {
      path: '',
      content: DEFAULT_CONTENT
    },
    editorContent: DEFAULT_CONTENT,
    isModified: false,
    settings: {
      fontSize: 16,
      editorWidth: 50,
      theme: 'light'
    },
    loading: false, // 初始化loading状态
    showEditor: true,
    showPreview: true
  }),
  
  actions: {
    async initSettings() {
      // 从 localStorage 初始化设置
      try {
        const raw = localStorage.getItem(LOCAL_STORAGE_KEY)
        if (raw) {
          const s = JSON.parse(raw)
          if (s && typeof s === 'object') {
            this.settings = {
              fontSize: typeof s.fontSize === 'number' ? s.fontSize : this.settings.fontSize,
              editorWidth: typeof s.editorWidth === 'number' ? s.editorWidth : this.settings.editorWidth,
              theme: s.theme === 'dark' || s.theme === 'light' ? s.theme : this.settings.theme
            }
          }
        }
      } catch (e) {
        console.warn('读取localStorage设置失败，使用默认值', e)
      }

      // 多窗口同步：监听其他窗口的 storage 事件
      try {
        window.addEventListener('storage', (ev: StorageEvent) => {
          if (ev.key === LOCAL_STORAGE_KEY) {
            try {
              const next = ev.newValue ? JSON.parse(ev.newValue) : null
              if (next && typeof next === 'object') {
                this.settings = {
                  fontSize: typeof next.fontSize === 'number' ? next.fontSize : this.settings.fontSize,
                  editorWidth: typeof next.editorWidth === 'number' ? next.editorWidth : this.settings.editorWidth,
                  theme: next.theme === 'dark' || next.theme === 'light' ? next.theme : this.settings.theme
                }
                // 同步DOM上的主题类
                this.applyThemeClass()
              }
            } catch {}
          }
        })
      } catch {}

      // 初始化完成后，同步一次DOM上的主题类，避免首次渲染不一致
      this.applyThemeClass()
    },

    // 将当前主题同步到根节点的class（#app）
    applyThemeClass() {
      try {
        const el = document.getElementById('app')
        if (!el) return
        if (this.settings.theme === 'dark') {
          el.classList.add('dark')
        } else {
          el.classList.remove('dark')
        }
      } catch {}
    },

    

    setCurrentFile(path: string, content: string) {
      this.currentFile = { path, content }
      this.editorContent = content
      this.isModified = false
    },
    
    updateEditorContent(content: string) {
      console.log('=== updateEditorContent被调用 ===')
      console.log('新内容长度:', content?.length || 0)
      console.log('当前文件内容长度:', this.currentFile.content?.length || 0)
      console.log('内容是否相同:', content === this.currentFile.content)
      
      this.editorContent = content
      // 只有当内容真正改变时才标记为已修改
      if (content !== this.currentFile.content) {
        console.log('内容发生变化，设置isModified为true')
        this.isModified = true
      } else {
        console.log('内容未发生变化，保持isModified状态')
      }
      console.log('最终isModified状态:', this.isModified)
    },
    
    setModified(modified: boolean) {
      this.isModified = modified
    },
    
    async updateSettings(newSettings: Partial<Settings>) {
      this.settings = { ...this.settings, ...newSettings }
      try {
        const payload = toPlainSettings(this.settings)
        localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(payload))
      } catch (e) {
        console.warn('保存设置到localStorage失败', e)
      }
    },
    
    async updateFontSize(value: number) {
      this.settings.fontSize = value
      try {
        const payload = toPlainSettings(this.settings)
        localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(payload))
      } catch (e) { console.warn('保存字体大小到localStorage失败', e) }
    },

    async updateEditorWidth(value: number) {
      this.settings.editorWidth = value
      try {
        const payload = toPlainSettings(this.settings)
        localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(payload))
      } catch (e) { console.warn('保存编辑器宽度到localStorage失败', e) }
    },
    
    async setTheme(value: 'light' | 'dark') {
      this.settings.theme = value
      try {
        const payload = toPlainSettings(this.settings)
        localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(payload))
      } catch (e) { console.warn('保存主题到localStorage失败', e) }
      // 同步DOM上的主题类
      this.applyThemeClass()
    },

    async toggleTheme() {
      console.log('store.toggleTheme被调用，当前主题:', this.settings.theme)
      this.settings.theme = this.settings.theme === 'light' ? 'dark' : 'light'
      console.log('store.toggleTheme执行后，新主题:', this.settings.theme)
      try {
        const payload = toPlainSettings(this.settings)
        localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(payload))
      } catch (e) { console.warn('保存主题到localStorage失败', e) }
      // 同步DOM上的主题类
      this.applyThemeClass()
    },
    
    // 添加设置loading状态的方法
    setLoading(loading: boolean) {
      this.loading = loading
    }

    // 视图显示/隐藏控制（会话级，不持久化）
    ,toggleEditorVisibility(): boolean {
      const next = !this.showEditor
      // 至少保留一个面板可见
      if (!next && !this.showPreview) {
        return false
      }
      this.showEditor = next
      return true
    }

    ,togglePreviewVisibility(): boolean {
      const next = !this.showPreview
      if (!next && !this.showEditor) {
        return false
      }
      this.showPreview = next
      return true
    }

    ,setPaneVisibility(payload: { editor?: boolean; preview?: boolean }) {
      const editor = payload.editor ?? this.showEditor
      const preview = payload.preview ?? this.showPreview
      // 若两者同时为false，则保持原状
      if (!editor && !preview) return
      this.showEditor = editor
      this.showPreview = preview
    }
  }
})